package Request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpClient {
    private String targetUrl;
    private static HttpURLConnection connection = null;

    public HttpClient() {
    }

    public HttpClient(String targetUrl) {
        this.targetUrl = targetUrl;
    }

    public String httpRequest() {
        return httpRequest(targetUrl);
    }

    public String httpRequest(String link) {
        StringBuilder content = new StringBuilder();
        try {
            URL url = new URL(link);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
            int code = connection.getResponseCode();
            if (code == 200) {
                InputStream in = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(isr);
                String line = null;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return content.toString();
    }
}
